'use strict';
const db = uniCloud.database()
const uniID = require('uni-id')
exports.main = async ({action,params,uniIdToken}, context) => {
	const collection = db.collection('address')
	const payload = await uniID.checkToken(uniIdToken)
	if (payload.code > 0) {
		return {
			code: 1001,
			msg: '用户身份验证失败，请重新登录'
		}
	}
	let res =null;
	if(action=="add"){
		params.user_id=payload.uid
		if(params.defaultFlag==1){
			await collection.where({user_id:payload.uid}).update({defaultFlag:0})
		}
		res = await collection.add(params)
	}else if(action=="get"){
		res = await collection.where({user_id:payload.uid}).orderBy("defaultFlag", "desc").get()
	}else if(action=="upd"){
		let id=params._id
		delete params._id
		if(params.defaultFlag==1){
			await collection.where({user_id:payload.uid}).update({defaultFlag:0})
		}
		res = await collection.where({_id:id,user_id:payload.uid}).update(params)
	}else if(action=="del"){
		res = await collection.where({_id: params._id}).remove()
	}
	return res
};

